<template>
	<view class="">
		<view v-show="!linkshow" class="">
			<view class="find-header">
				<view class="find-header-img">
					<image mode="widthFix" src="https://statics.xmcsrv.net/weixin/wifi/connectWifi.png" alt="" />
				</view>
				<view class="hint-text">
					如果你的Wi-Fi是 5GHz 的，请先设置为 2.4GHz
				</view>
			</view>
			<view class="" style="text-align: center;padding: 0 20rpx;">
				<uni-easyinput prefixIcon="tune" class="find-input" v-model="wifiName" placeholder="请输入WIFI名称">
				</uni-easyinput>
				<!-- <view v-if="!wifiName" class="wifiTips">获取不到wifi名称时请手动开启定位后进页面重试</view> -->
				<uni-easyinput type="password" prefixIcon="locked" class="find-input" suffixIcon="eye" v-model="wifiPwd"
					placeholder="请输入你的密码"></uni-easyinput>
			</view>
			<view class="find-hint">
				*选择较强信号的WIFI，正确填写WIFI密码，可快速让设备联网
			</view>
			<view class="find-food">
				<view class="find-food-hint" @click="showConnectInfo">
					联网遇到问题？
				</view>
				<button class="radius-btn" @tap="onBindtapsubmit()" type="operation">确定</button>
			</view>
		</view>
		<view v-show="linkshow" class="">
			<view class="u-f-ajc top" style="">
				<image class="scanImg" src="https://statics.xmcsrv.net/weixin/searchBle.gif"></image>
				<view class="time">{{time}}'</view>
			</view>
			<template v-if="isLinked">
				<view class="find-success-hint">
					1.连接蓝牙设备成功！
				</view>
				<view v-if="isReceived" class="find-success-hint">
					2.设备已成功接收配网信息！
				</view>
				<view v-if="isReceived && !isDistributeNet" class="find-success-hint">
					3.等待设备连接路由器...
				</view>
				<view v-if="isReceived && isDistributeNet" class="find-success-hint">
					3.配网成功
				</view>
				<!-- <view class="find-success-hint">{{isDistributeNet?'3.配网成功':'3.等待设备连接路由器...'}}</view> -->
			</template>
			<template v-else>
				<view class="find-success-hint">正在连接蓝牙设备...</view>
			</template>
			<view class="find-food">
				<button data-code="601114" data-eventNaem="blue_config_user_cancel" class="radius-btn" type="operation" @tap="cancellink">取消</button>
			</view>
		</view>
		<uni-popup ref="popup" class="popupName">
			<view class="popup-from">
				<view class="title">提示</view>
				<view class="message">您还没有输入WiFi密码，确定要继续？</view>
				<view class="popup-button">
					<button @tap="close()" class="cancel">取消</button>
					<button @tap="confirm()" class="block radius-btn" type="primary">确定</button>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="connectPopup">
			<view class="popup-connect" style="width: 600rpx;">
				<view class="popup-header">
					<text class="p-title">以下问题可能导致设备联网失败</text>
					<uni-icons class="close" type="closeempty" color="#AFAFAF" @click="closeConnectInfo"></uni-icons>
				</view>
				<view class="u-f-c popup-content">
					<text>1、检查是否开启WiFi防蹭网(此设置可能会导致设备无法正常联网)，可临时关闭，设备联网成功后再开启;</text>
					<text>2、如果您家是双频路由器，请检查摄像连接的WiFi是否是5GHz频段的WiFi，请切换连接2.4GHz频段的WiFi;</text>
					<text>3、如果您家的WiFi是桥接的(因为桥接的原因可能会导致网络不稳定)，建议连接非桥接WiFi;</text>
					<text>4、如果您的设备、路由器、手机，距离过远，或者中间有墙壁等障碍物，建议尽可能靠近</text>
				</view>
				<view class="popup-tips">温馨提示:选择较强信号的 WiFi，可快速让设备联网</view>
			</view>
		</uni-popup>
		<uni-popup ref="questionPopup">
			<view class="popup-connect" style="width: 600rpx;padding-bottom: 5px;">
				<view class="popup-header">
					<text class="p-title">设备连接遇到问题</text>
					<uni-icons class="close" type="closeempty" color="#AFAFAF" @click="closecode()"></uni-icons>
				</view>
				<view class="u-f-c popup-content">
					<text>1、请插好电源和数据线，确保设备上电并已经正常运行;</text>
					<text>2、首次配网，请将设备，手机和路由器置于1米以内的范围，确保信号接收成功;</text>
					<text>3、待观察到设备指示灯红灯快闪，并听到“等待连接”语音提示，方可开始配置;</text>
					<text>4、如未观察到上述现象，请长按设备SET/RESET键，将设备恢复出厂设置后重新连接</text>
					<text style="color: #FF0025;">注：全景灯泡为灯体闪烁，且无语音提示</text>
				</view>
				<view class="popup-buttons">
					<button @tap="closecode()" class="block radius-btn" type="primary">我知道了</button>
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script>
	const {
		hexStringToArrayBuffer,
		ab2hex,
		hexToString,
		strToHex
	} = require('@/utils/util.js');
	const { stringToUTF8Bytes,useStrFill,stringToByte,strToHexCharCode } = require('@/jvss/pagesDevice/utils/index.js');
	import {
		buletoothCodeMsg
	} from '@/utils/errorCode.js'
	export default {
        // watch: {
        //     linkshow: {
        //         handler(n, o) {
        //             if(n === false) {
        //                 console.log('配网界面被关闭')
        //                 this.cancellink()
        //             }
        //         }
        //     }
        // },
		data() {
			return {
				wifiName: '',
				wifiPwd: '',
				linkshow: false,
				device: {},
				serviceId: '00001910-0000-1000-8000-00805f9b34fb',
				characteristicId: '00002b10-0000-1000-8000-00805f9b34fb',
				notifyId: '00002b10-0000-1000-8000-00805f9b34fb',
				isLinked: false, //连接蓝牙
				isReceived: false, //设备收到消息
				isDistributeNet: false, //配网
				time: 180,
				timerId: null,
				showPwd: true,
				isUnload: false,
				version: 'v1',
				maxMTU: 512,
				buffer: '',
				createBLEConnectionNum:0,//部分手机连接失败重试 2
			}
		},
		onUnload() {
			console.log('退出');
			this.isUnload = true
			this.cancellink()
			wx.stopWifi({
				success(res) {
					console.log(res.errMsg)
				}
			})
		},
		onLoad(opt) {
			this.device = JSON.parse(opt.device)
			//v2版本协议
			if (this.device.advertisDataStr&&(this.device.advertisDataStr.endsWith('03') || this.device.advertisDataStr.endsWith('02'))) {
				this.version = 'v2'
			}
			console.log(this.device, '接收');
			this.startWifi();
			this.$postPointData({code:'601101', eventName:'start_blue_config'})
			this.$logs({
				info: '开始蓝牙配网接收opt！',
				device: this.device,
				version:this.version
			})
		},
		onShow() {
			this.$postPointData({code:'601111', eventName:'click_blue_dev_set_router_confirm'})
			console.log(this.isUnload, 'this.isUnload')
		},
		methods: {
			//确定
			onBindtapsubmit() {
				if (!this.wifiName) {
					return uni.showToast({
						title: '请输入WiFi名称',
						icon: 'none'
					})
				}
				if (!this.wifiPwd) {
					this.$refs.popup.open()
					return
				}
				let data = {
					wifiName: this.wifiName,
					wifiPwd: this.wifiPwd
				}
				uni.setStorageSync('wifiInfo', data);
				uni.showLoading({
					mask:true
				})
				setTimeout(()=>{
					uni.hideLoading();
					this.createBLEConnectionNum = 0
					this.linkshow = true;
					this.createBLEConnection()
				},866)
			},
			close() {
				this.$refs.popup.close();
			},
			iconClick() {
				console.log('ddd');
				this.showPwd = this.showPwd
			},
			//联网遇到的问题弹框
			showConnectInfo() {
				this.$refs.connectPopup.open();
			},
			closeConnectInfo() {
				this.$refs.connectPopup.close();
			},
			// 连接超时弹窗
			closecode() {
				this.cancellink()
				this.$refs.questionPopup.close();
			},
			//取消配网
			cancellink() {
				uni.hideLoading();
				clearInterval(this.timerId)
				this.linkshow = false;
				this.isLinked = false;
				this.isReceived = false;
				this.time = 180
				this.closeBLEConnection()
			},
			//连接蓝牙
			confirm() {
				this.linkshow = true;
				this.$refs.popup.close();
				this.createBLEConnection()
			},
			// 设置倒计时
			setTime() {
				this.timerId = setInterval(() => {
					this.time--;
					if (this.time <= 0) {
						clearInterval(this.timerId);
						uni.hideLoading();
						setTimeout(() => {
							this.$refs.questionPopup.open();
						}, 200)
						// uni.showModal({
						// 	title:'提示',
						// 	content:'未发现蓝牙设备,请将手机靠近设备后重试',
						// 	confirmColor:'#FF0025',
						// 	showCancel:false,
						// 	success: (res) => {
						// 		if(res.confirm){
						// 			this.cancellink()
						// 		}
						// 	}
						// })
					}
				}, 1000)
			},
			//初始化 Wi-Fi 模块
			startWifi() {
				wx.startWifi({
					success: (res) => {
						// this.onWifiConnect()
						this.getConnectedWifi()
					},
					fail: (err) => {
						console.log('wifierr:', err);
					}
				})
			},
			getConnectedWifi() {
				wx.getConnectedWifi({
					success: res => {
						this.wifiName = res.wifi.SSID
						let wifiInfo = uni.getStorageSync('wifiInfo')
						if (wifiInfo && wifiInfo.wifiName == this.wifiName) {
							this.wifiPwd = wifiInfo.wifiPwd
						}
					},
					fail: (err) => {
						console.log('获取wifi信息失败', err);
						this.$logs({
							info: '获取wifi信息失败',
							err: err
						})
						uni.showToast({
							title: 'Wi-Fi信息获取失败，请确认手机定位开关与权限是否打开，或手动输入Wi-Fi名称与密码',
							icon: 'none',
							duration: 2500
						})
					}
				})
			},
			//监听连接上 Wi-Fi 的事件
			onWifiConnect() {
				wx.onWifiConnectedWithPartialInfo((res) => {
					this.wifiName = res.wifi.SSID
				})
			},
			// 初始化蓝牙模块
			openBluetoothAdapter(callback){
				uni.openBluetoothAdapter({
					success: (e) => {
						if(typeof callback == 'function'){
							callback()
						}
					}
				})
			},
			// 连接低功耗蓝牙
			createBLEConnection(type) {
				this.$postPointData({code:'601105'})
				if(!type) this.setTime()
				let deviceId = this.device.deviceId;
				// uni.showToast({
				// 	title: '连接蓝牙...',
				// 	icon: 'loading',
				// 	duration: 99999
				// });
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId,
					timeout: 3 * 60000,
					success: res => {
						// 连接设备后断开搜索 并且不能搜索设备
						// uni.hideToast();
						// uni.showToast({
						// 	title: '连接蓝牙设备成功！',
						// 	icon: 'success',
						// 	duration: 2000
						// });
						this.isLinked = true
						this.stopBluetoothDevicesDiscovery()
						if (this.version == 'v1') {
							this.setBLEMTU()
						}
						this.getBLEDeviceServices()
						this.$logs({
							info: '蓝牙配网连接成功！',
							deviceId: this.device.deviceId,
							res: res
						})
					},
					fail: e => {
						uni.hideToast();
						this.$postPointData({code:'401102', eventName:'bluetooth_connect_respond_failed',error_code:e.errCode})
						if(e.errCode == 10000){
							this.openBluetoothAdapter(()=>{
								this.createBLEConnection('retry')
							})
						}
						if(e.errCode == 10003){
							this.createBLEConnectionNum++
							this.isLinked = false;
							if(this.createBLEConnectionNum < 2){
								this.createBLEConnection('retry')
							}else{
								this.linkshow = false;
							}
							// this.cancellink();
                            // if(!this.isUnload){
                            //     uni.showToast({
                            //     title:'连接蓝牙失败',
                            //     icon:'error',
                            //     duration:2000
                            // })
                            // }
						}
						this.$logs({
							info: '蓝牙配网连接蓝牙失败！',
							deviceId: this.device.deviceId,
							error: e,
							createBLEConnectionNum:this.createBLEConnectionNum
						})
						console.log('连接低功耗蓝牙失败，错误码：' + e.errCode);
					}
				});
			},
			// 获取初始化信息
			writeBlueDataInit() {
				// let str = this.combineFlame()
				// let flameContent = ''
				let stringBuilder = '8B8B02010009000000'
				// // let wifiNameSizeFill = useStrFill(wifiNameSize.toString(16),2,'0',true) 
				// // let wifiPwdSizeFill = useStrFill(wifiPwdSize.toString(16),2,'0',true)
				// // let pwdTypeFill = useStrFill(pwdType.toString(16),2,'0',true)
				// // let wifiPwdStr = strToHexCharCode(wifiPwd)
				// flameContent = `${wifiNameSizeFill}${wifiNameStr}${wifiPwdSizeFill}${wifiPwdStr}${pwdTypeFill}`
				// let flameContentFill = useStrFill(((flameContent.length)/2).toString(16),4,'0',true)
				// stringBuilder =`${stringBuilder}${flameContentFill}${flameContent}` 
				let checkCode = this.createCheckCode(stringBuilder)
				stringBuilder = `${stringBuilder}${checkCode}`
				// console.log('wifi===',wifiName,wifiNameStr,wifiNameSize,wifiNameSizeFill,wifiPwdSizeFill);
				// console.log('wifiPwd===',wifiPwd,wifiPwdStr,wifiPwdSize,wifiPwdSizeFill,pwdTypeFill);
				// console.log('1111===',flameContent,flameContent.length,flameContentFill,stringBuilder,checkCode);
				console.log('stringBuilder', stringBuilder.toUpperCase());

				let str = stringBuilder.toUpperCase()
				this.writeBluetoothData(str)
				this.$logs({
					info: '向蓝牙设备写数据v2',
					data: str
				})
			},
			//向蓝牙写数据
			writeBlueData() {
				// 向蓝牙设备发送数据
				let str = this.combineFlame()
				if (this.version == 'v2') {
					let splice = Math.ceil(str.length / this.maxMTU)
					for (var i = 0; i < splice; i++) {
						let data = str.substring(i * this.maxMTU, this.maxMTU + i * this.maxMTU)
						console.log('向蓝牙写数据===v2', data);
						this.writeBluetoothData(data)
					}
				} else {
					this.writeBluetoothData(str)
				}

				this.$logs({
					info: '向蓝牙设备写数据v1',
					data: str
				})
			},
			writeBluetoothData(str) {
				let deviceId = this.device.deviceId;
				let serviceId = this.serviceId;
				let characteristicId = this.characteristicId;
				uni.writeBLECharacteristicValue({
					deviceId,
				 serviceId,
					characteristicId,
					// 这里的value是ArrayBuffer类型
					value: hexStringToArrayBuffer(str),
					writeType: 'write',
					success: (res) => {
						this.isReceived = true
						// uni.showLoading({title:'连接中' })
					},
					fail: (err) => {
						console.log('write err', JSON.stringify(err));
					}
				})
			},
			//订阅notify
			notifyBLECharacteristicValue(deviceId, serviceId, characteristicId) {
				uni.notifyBLECharacteristicValueChange({
				 state: true, // 启用 notify 功能
					deviceId,
					serviceId,
					characteristicId,
					success: (res) => {
				 	console.log('notifyBLECharacteristicValueChange success', res)
						this.onBLECharacteristicValue()
					}
				})
			},
			//监听设备端回调的数据
			onBLECharacteristicValue() {
				uni.onBLECharacteristicValueChange(res => {
					console.log('监听蓝牙设备发过来的数据:', res)
					let resHex = ab2hex(res.value)
					console.log('回调value：', resHex);
					console.log(resHex.length);
					this.createCheckCode('010014')
					if (this.version == 'v2') {
						if (resHex.substring(0, 4) == '0009' && resHex.substring(10, 12) == '01') {
							this.maxMTU = parseInt(resHex.substring(12, 16), 16)
							this.setBLEMTU(this.maxMTU, this.writeBlueData())
							this.buffer = ''
						} else {
							if (resHex.startsWith('8b8b0203') && !this.buffer) {
								this.buffer = resHex
							}
							if (this.buffer) {
								this.buffer = this.buffer + resHex
							}
							console.log('this.buffer===',this.buffer);
							if (this.buffer.lastIndexOf('8b8b0203') > 0) {
								let idx = this.buffer.lastIndexOf('8b8b0203')
								this.parseBleConfigResult(this.buffer.slice(0, idx))
								this.buffer = this.buffer.slice(idx)
							}
						}
					} else {
						if (resHex.length < 25) {
							//回调成功
							console.log(resHex.substring(18, 20));
							console.log(resHex.substring(18, 20) == '00');
							if (resHex.substring(18, 20) == '00') {
								this.isReceived = true
								if (this.time < 1) {
									this.isLinked = false
									this.linkshow = false
									this.cancellink()
									this.$postPointData({code:'401117', eventName:'bluetooth_connect_wifi_failed_unknown',error_code:resHex.substring(18, 20),data:resHex})
									uni.showToast({
										title: '配网失败',
										icon: 'none',
										duration: 1500,
									})
									// this.closeBLEConnection()
								}
							} else if (resHex.substring(18, 20) == '53') {
								let obj ={code:'401114', eventName:'bluetooth_connect_wifi_failed_pwd_error',error_code:resHex.substring(18, 20),data:resHex}
								this.$postPointData(obj)
								uni.showModal({
									title: '提示',
									content: '设备连接路由器失败，路由器密码错误，请输入正确密码后重新配网',
									confirmColor: '#FF0025',
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											this.isLinked = false;
											this.isReceived = false;
											this.cancellink();
										}
									}
								})
							}
						} else {
							//配网成功
							console.log(resHex.substring(18, 20) == '00');
							if (resHex.substring(18, 20) == '00') {
								clearInterval(this.timerId)
								this.isDistributeNet = true
								this.$postPointData({code:'601100', eventName:'blue_sys_add_dev_success'})
								uni.showToast({
									title: '配网成功',
									icon: 'success',
									duration: 2000
								});
								//解析结果
								this.parseBleConfigResult(resHex.slice(18))
							} else {
								uni.showToast({
									title: buletoothCodeMsg[Number(resHex.substring(18, 20))],
									icon: 'none',
									duration: 2000
								});
							}
						}
					}
					this.$logs({
						info: '监听蓝牙设备发过来的数据',
						resHex: resHex,
						res: res
					})
					// //解析结果
					// this.parseBleConfigResult(resHex.slice(18))
				})
			},
			// 获取所有服务
			getBLEDeviceServices() {
				let deviceId = this.device.deviceId;
				uni.getBLEDeviceServices({
					deviceId,
					success: res => {
						this.serviceId = res.services[0].uuid
						this.getBLEDeviceCharacteristics()
					},
					fail: e => {
						console.log('获取设备服务失败，错误码：' + e.errCode);
					}
				});
			},
			// 获取某个服务下的所有特征值
			getBLEDeviceCharacteristics() {
				let deviceId = this.device.deviceId;
				let serviceId = this.serviceId;
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: res => {
						console.log('获取特征', JSON.stringify(res));
						for (var i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i]
							//订阅notify
							if (item.properties.notify || item.properties.indicate) {
								this.notifyBLECharacteristicValue(deviceId, serviceId, item.uuid)
							}
							//写数据
							if (item.properties.write) {
								this.characteristicId = item.uuid
								if (this.version == 'v1') {
									this.writeBlueData()
								} else if (this.version == 'v2') {
									setTimeout(() => {
										this.writeBlueDataInit()
									}, 200)
								}
							}
						}
					},
					fail: e => {
						console.log('获取特征值失败，错误码：' + e.errCode);
					}
				});
			},
			// 设置蓝牙低功耗的最大传输单元
			setBLEMTU(num, callback) {
				let deviceId = this.device.deviceId;
				let mtu = num || 512;
				uni.setBLEMTU({
					deviceId,
					mtu,
					success: (res) => {
						console.log('setBLEMTU成功:' + JSON.stringify(res));
						if (typeof callback == 'function') {
							callback()
						}
					}
				})
			},
			// 停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: e => {
						console.log('停止搜索蓝牙设备:' + e.errMsg);
					}
				});
			},
			// 断开与低功耗蓝牙设备的连接
			closeBLEConnection() {
				let deviceId = this.device.deviceId;
				uni.closeBLEConnection({
					deviceId,
					success: res => {
						console.log(res);
						// uni.showToast({
						// 	title: '断开成功',
						// 	icon: 'success',
						// 	duration: 2000
						// });
					},
					fail: e => {
						console.log('断开低功耗蓝牙成功，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							// initTypes(e.errCode);
						}
					}
				});
			},
			//写入蓝牙的数据（16进制字符串）
			combineFlame() {
				this.$postPointData({code:'601106'})
				let flameContent = ''
				let stringBuilder = '8B8B0101000200'
				let wifiName = this.wifiName
				let wifiNameSize = stringToByte(wifiName).length
				let wifiPwd = this.wifiPwd
				let wifiPwdSize = stringToByte(wifiPwd).length
				let pwdType = '0'
				let wifiNameSizeFill = useStrFill(wifiNameSize.toString(16), 2, '0', true)
				let wifiPwdSizeFill = useStrFill(wifiPwdSize.toString(16), 2, '0', true)
				let pwdTypeFill = useStrFill(pwdType.toString(16), 2, '0', true)
				let wifiNameStr = stringToUTF8Bytes(wifiName)
				let wifiPwdStr = strToHexCharCode(wifiPwd)
				flameContent = `${wifiNameSizeFill}${wifiNameStr}${wifiPwdSizeFill}${wifiPwdStr}${pwdTypeFill}`
				let flameContentFill = useStrFill(((flameContent.length) / 2).toString(16), 4, '0', true)
				stringBuilder = `${stringBuilder}${flameContentFill}${flameContent}`
				let checkCode = this.createCheckCode(stringBuilder)
				stringBuilder = `${stringBuilder}${checkCode}`
				// console.log('wifi===',wifiName,wifiNameStr,wifiNameSize,wifiNameSizeFill,wifiPwdSizeFill);
				// console.log('wifiPwd===',wifiPwd,wifiPwdStr,wifiPwdSize,wifiPwdSizeFill,pwdTypeFill);
				// console.log('1111===',flameContent,flameContent.length,flameContentFill,stringBuilder,checkCode);
				console.log('stringBuilder', stringBuilder.toUpperCase());
				return stringBuilder.toUpperCase()
			},
			
			//解析最终结果
			parseFinallyResult(hexData){
				console.log('解析最终结果parseFinallyResult',hexData);
				let sLen = 0
				let eLen = 0
				//随机设备登录名长度
				let userNameLen = parseInt(hexData.substring(2, 4), 16)
				//随机设备登录名
				sLen = 4;
				eLen = userNameLen * 2 + 4;
				let userName = hexData.substring(sLen, eLen);
				let userNameByte = stringToByte(userName)
				//随机密码长度
				sLen = userNameLen * 2 + 4;
				eLen = userNameLen * 2 + 6;
				let passwordLen = parseInt(hexData.substring(sLen, eLen), 16);
				//随机密码
				sLen = userNameLen * 2 + 6;
				eLen = passwordLen * 2 + userNameLen * 2 + 6;
				let password = hexData.substring(sLen, eLen); /////////
				//设备序列号长度
				sLen = passwordLen * 2 + userNameLen * 2 + 6;
				eLen = passwordLen * 2 + userNameLen * 2 + 8;
				let devIdLen = parseInt(hexData.substring(sLen, eLen), 16);
				//设备序列号
				sLen = passwordLen * 2 + userNameLen * 2 + 8;
				eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 8;
				let devId = hexData.substring(sLen, eLen); ///////////////
				console.log('devid===', hexToString(devId));
				//设备IP地址
				sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 8;
				eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 16;
				let devIp = hexData.substring(sLen, eLen);
				
				//设备MAC地址
				sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 16;
				eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 28;
				let mac = hexData.substring(sLen, eLen);
				let tokenLen = 0;
				let token = null;
				if (hexData.length > eLen) {
					//获取设备登录Token长度
					sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 28;
					eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 30;
					tokenLen = parseInt(hexData.substring(sLen, eLen), 16)
				
					//获取设备登录Token
					sLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 30;
				 eLen = passwordLen * 2 + userNameLen * 2 + devIdLen * 2 + 30 + tokenLen * 2;
					token = hexData.substring(sLen, eLen);
				}
				console.log('userName:', userName, 'passwordLen:', passwordLen, 'password:', password, 'devIdLen:',
					devIdLen, 'devId:', devId, 'devIp:', devIp, 'mac:', mac, 'tokenlenL=:', tokenLen, 'token:',
					token);
				let data = {
					deviceNo: hexToString(devId),
					deviceType: this.device.deviceInfo.description,
					pid: this.device.pid,
					devicePic: this.device.deviceInfo.devicePic,
					adminToken: token ? hexToString(token) : ''
				}
				uni.hideLoading()
				wx.reLaunch({
					url: `/jvss/pagesDevice/device/bluetooth/equipment-rename?device=${encodeURIComponent(JSON.stringify(data))}&connecttype=bluetooth`
				})
				this.$postPointData({code:'601109', eventName:'blue_config_get_system_info_success'})
				this.$logs({
					info: '蓝牙配网成功',
					data: hexData,
					userName: userName,
					passwordLen: passwordLen,
					password: password,
					devIdLen: devIdLen,
					devId: devId,
					devIp: devIp,
					mac: mac,
					tokenlenL: tokenLen,
					token: token,
					deviceNo: hexToString(devId),
					deviceType: this.device.deviceInfo.description
				})
			},
			// 解析蓝牙配网结果
			parseBleConfigResult(data) {
				console.log('解析蓝牙配网结果parseBleConfigResult:', data);
				let hexData = ''
				if(this.version == 'v2'){
					let checksum = data.slice(data.length - 2)
					let content = data.slice(0, data.length - 2)
					let cChecksum = this.createCheckCode(content)
					hexData = data.slice(18)
					console.log('解析蓝牙配网结果校验和:', checksum,cChecksum,data.substring(18,20));
					if((checksum == cChecksum)&&data.substring(18,20)=='00'){
						this.isReceived = true
						this.parseFinallyResult(hexData)
						clearInterval(this.timerId)
						this.isDistributeNet = true
						uni.showToast({
							title: '配网成功',
							icon: 'success',
							duration: 2000
						});
					}else if(data.substring(18,20)=='50'){
						this.showErrTotast('配网失败-未知错误')
					}else if(data.substring(18,20)=='53'){
						this.showErrTotast('路由器密码错误')
					}else if(data.substring(18,20)=='55'){
						this.showErrTotast('配网失败-未知错误')
					}
				}else{
					hexData = data//data.substring(0, 2)
					let connectResult = hexData.substring(0, 2)
					if (connectResult == '00') {
						this.parseFinallyResult(hexData)
					} else if (connectResult == '53') {
						//配网失败，路由器密码错误
						this.showErrTotast('路由器密码错误')
					} else {
						//其他错误，设备端会一直重试
					}
				}
				this.$logs({
					info: '蓝牙配网结果',
					data: hexData
				})
			},
			showErrTotast(msg){
				uni.showToast({
					title: msg,
					icon: 'error',
					duration: 2000
				});
			},
			//校验和
			createCheckCode(str) {
				let total = 0
				for (var i = 0; i < str.length / 2; i++) {
					let currentI = i * 2
					let i12 = currentI + 2
					let subString = str.substring(currentI, i12)
					total += parseInt(subString, 16)
				}
				let result = useStrFill((total % 256).toString(16), 2, '0', true)
				console.log('校验和', result);
				return result
			},


		}
	}
</script>

<style lang="scss" scoped>
	.popupName {
		/deep/ .uni-popup__wrapper {
			top: -100rpx;
		}
	}

	/deep/.uniui-eye-slash-filled:before {
		content: "\e66a";
	}

	/deep/.uniui-eye-filled:before {
		content: "\e6b4";
	}

	/deep/ .uni-easyinput {
		margin-top: 20rpx;
	}

	.top {
		position: relative;
		margin: 100rpx 0;

		.scanImg {
			width: 300rpx;
			height: 300rpx;
		}

		.time {
			font-size: 30rpx;
			font-weight: 700;
			color: white;
			z-index: 9;
			position: absolute;
			left: 0;
			right: 0;
			text-align: center
		}
	}

	.find-success-hint {
		font-size: 28rpx;
		color: #707070;
		text-align: center;
	}

	.popup-from {
		background-color: #fff;
		padding: 60rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.wifiTips {
		color: red;
		font-size: 22rpx;
		display: flex;
		// margin-left: 20rpx;
	}

	.title {
		font-size: 34rpx;
		font-weight: bold;
		line-height: 48rpx;
		color: #464646;
	}

	.message {
		font-size: 30rpx;
		line-height: 30rpx;
		color: #9A9A9A;
		width: 450rpx;
		margin: 60rpx 0;
	}

	.popup-button {
		display: flex;
	}

	.popup-connect {
		background-color: #fff;
		// padding: 20rpx;
		border-radius: 10rpx;
		text-align: center;
	}

	.popup-header {
		position: relative;
		border-bottom: 1rpx solid #EEEEEE;
		padding: 20rpx;

		.p-title {
			font-size: 26rpx;
		}

		.close {
			position: absolute;
			right: 10rpx;
			top: 30rpx;
		}
	}

	.popup-content {
		padding: 30rpx;
		height: 350rpx;
		overflow: scroll;
		text-align: left;

		text {
			margin-top: 20rpx;
			color: #AFAFAF;
			font-size: 24rpx;
		}
	}

	.popup-tips {
		border-top: 1rpx solid #EEEEEE;
		padding: 20rpx;
		color: #FF0025;
		font-size: 26rpx;
		text-align: center;
	}

	.popup-button button {
		width: 200rpx !important;
		height: 80rpx;
		border-radius: 40px;
		border: none;
		font-size: 30rpx;
	}

	.popup-buttons button {
		width: 90% !important;
		height: 80rpx;
		border: none;
		font-size: 30rpx;
	}

	.find-header {
		margin-bottom: 50rpx;
	}

	.find-header-img {
		// width: 100px;
		// height: 100px;
		// margin: auto;
		margin-top: 60px;
		margin-bottom: 30px;
		text-align: center;
	}

	.find-header-img image {
		width: 400rpx;
	}

	.hint-text {
		font-size: 22rpx;
		color: #444444;
		line-height: 29rpx;
		text-align: center;
	}

	.find-type {
		display: flex;
		justify-content: center;
		font-size: 30rpx;

	}

	.find-type-t {
		color: #FF0025;
		margin-right: 20rpx;
	}

	.find-type-f {
		color: #F8716B;
	}

	.find-type-icons {
		text-align: center;
	}

	.find-hint {
		font-size: 16rpx;
		line-height: 15px;
		color: #444444;
		opacity: 0.8;
		margin-left: 2%;
	}

	.uni-easyinput {
		width: 96% !important;
		height: 80rpx;
		background: #fff;
		border-radius: 16rpx;
		margin: 20rpx auto;
	}

	.uni-easyinput .is-input-border {
		border: none;
	}

	.find-food {
		text-align: center;
		position: fixed;
		bottom: 50rpx;
		width: 100%;
		font-size: 28rpx;
	}

	.find-food-hint {
		color: #FF0025;
		margin-bottom: 40rpx;
	}
</style>
